var $btnAddToggle = $('#btnAddToggle');
var $editDialog = $('#editDialog');
var $model = $('#model');
var $btnSave = $('#btnSave');
var $editForm = $('#editForm');

$(function(){
	initModelData('');
	
	$btnAddToggle.on('click',function(){
		openAddDialog();
	});
	
	$btnSave.on('click',function(){
		doSave();
	});
})

function openAddDialog(){
	$model.chosen({alow_single_deselect: true, width:'100%'});
	$editDialog.modal('show');
}

function doSave(){
	var data = $editForm.serializeObject();
	var paramData = JSON.stringify(data);
	doPost(paramData);
}

function initModelData(modelData){
	$.ajax({
		url: 'types',
		type: 'GET',
		contentType: 'application/json;charset=utf-8',
		dataType: 'json',
		success:function(result){
			if(result.success){
				var types = result.rows;
				for(var i=0;i<types.length;i++){
					$model.append($('<option></option>').val(types[i].name).html(types[i].name));
				}
			}
		},
		error:function(request,status,error){
			toastr.error(error, '矿机类型下拉列表数据获取失败');
		}
	});
}

function doPost(paramData){
	$.ajax({
		url: 'macmodels',
		type: 'POST',
		dataContent: 'application/json;charset=utf-8',
		dataType: 'json',
		success: function(result){
			if(result.success){
				alert('添加成功');
			}else{
				toastr.error(result.message, '添加失败');
			}
		},
		error: function(request,status,error){
			toastr.error(error, '异常');
		}
	});
}